import React, { useState, useRef, useEffect } from 'react'
import Avatars from '../../component/avatars'
import { UserIcon } from '../../utils/icons';
import "./setting.scss"
import { Tabs, InputNumber, TimePicker, Button, Input, Modal, Cascader, Spin } from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import { SET_LANGUAGE } from '../../store/actionTypes'
import Forms from "./form"
import FormPay from "./form_pay"
import dayjs from 'dayjs'

const format = 'HH:mm';
const format1 = 'HH';

export default function Setting() {

  const username = useSelector((state) => state.userReducer.user.username)

  const [timeValue, setTimeValue] = useState("00:00")
  const [timeValue1, setTimeValue1] = useState("00")
  const [referrer, setReferrer] = useState({})
  const [telephone, setTelephone] = useState(null)
  const change_input = (value) => {
    console.log('changed', value);
  };
  const change_time = (time, dateString) => {
    console.log('changed', dateString);
    setTimeValue(dateString)
  };
  const change_time1 = (time, dateString) => {
    console.log('changed', time, dateString);
    setTimeValue1(dateString)
  };
  function gePass(pass) {
    let passWord = ""
    String(pass).split("").forEach(item => passWord += "*")
    return passWord;
  }

  const languages = useSelector((state) => state.publicReducer.language)
  const dispatch = useDispatch()
  const [spin, setSpin] = useState(false)
  const options = [
    {
      value: 'Korean',
      label: 'Korean',
    },
    {
      value: 'Chinese',
      label: 'Chinese',
    },
    {
      value: 'English',
      label: 'English',
    },
  ];
  const CascaderChange = (value) => {
    setSpin(true)
    setTimeout(() => {
      setSpin(false)
      dispatch({ type: SET_LANGUAGE, payload: value[0] })
    }, 2000)
  };

  const changeTel = (e) => {
    setTelephone(e.target.value)
  }

  const tabChange = (key) => {
    console.log(key);
  };

  const item_pay = [
    {
      label: `XRP`,
      key: '1',
      children: <div className='Tabs'>
        <FormPay labels={{ label1: languages === "Korean" ? "My XRP 주소" : (languages === "Chinese" ? "My XRP 地址" : "My XRP address"), label2: languages === "Korean" ? "데스티네이션 테그" : (languages === "Chinese" ? "1회 최대 거래금액" : "Destination tag"), Submit: languages === "Korean" ? "수정" : (languages === "Chinese" ? "编辑" : "Edit"), remember: true }}></FormPay>
      </div>
    },
    {
      label: `EOS`,
      key: '2',
      children: <div className='Tabs'>
        <FormPay labels={{ label1: languages === "Korean" ? "My EOS 주소" : (languages === "Chinese" ? "My EOS 地址" : "My EOS address"), label2: "MEMO", Submit: languages === "Korean" ? "수정" : (languages === "Chinese" ? "编辑" : "Edit"), remember: false }} ></FormPay>
      </div>
    },
  ]

  const items = [
    {
      label: languages === "Korean" ? "거래설정 보기" : (languages === "Chinese" ? "交易设置" : "Trade setting"),
      key: '1',
      children: <div className='tabs_main'>
        <ul>
          <li><b>{languages === "Korean" ? "1회 최대 거래금액" : (languages === "Chinese" ? "单笔最大交易金额" : "Maximum single transaction amount")}</b>
            <InputNumber
              size="large"
              defaultValue={100}
              min={100}
              formatter={(value) => `${value}${languages === "Korean" ? "만원" : (languages === "Chinese" ? "韩元" : "won")}`}
              parser={(value) => value.replace('00' + languages === "Korean" ? "만원" : (languages === "Chinese" ? "韩元" : "won"), '')}
              onChange={change_input}
            /></li>
          <li><figure><Button type="primary">
            {languages === "Korean" ? "일반 거래" : (languages === "Chinese" ? "一般交易" : "General transaction")}
          </Button><Button>
              {languages === "Korean" ? "안전 거래" : (languages === "Chinese" ? "安全交易" : "Secure transactions")}
            </Button></figure></li>
          <li><b>{languages === "Korean" ? "거래소 가격차이" : (languages === "Chinese" ? "交易所价格差异" : "Exchange price difference")}</b>
            <InputNumber
              size="large"
              defaultValue={0.1}
              min={0.1}
              max={1}
              step="0.1"
              formatter={(value) => `${value}%`}
              parser={(value) => value.replace('%', '')}
              onChange={change_input} /></li>
          <li><b>{languages === "Korean" ? "거래당 수익범위" : (languages === "Chinese" ? "交易所收益范围" : "Exchange income range")}</b>
            <InputNumber
              size="large"
              defaultValue={0.1}
              min={0.1}
              max={1}
              step="0.1"
              formatter={(value) => `${value}%`}
              parser={(value) => value.replace('%', '')}
              onChange={change_input} /></li>
          <li><b>{languages === "Korean" ? "일별 결산 시간" : (languages === "Chinese" ? "每日结算时间" : "Daily settlement time")}</b>
            <TimePicker allowClear={false} showNow={false} value={dayjs(timeValue, format)} onChange={change_time} size="large" format={format} /></li>
          <li><figure><Button type="primary">
            {languages === "Korean" ? "자동 청산" : (languages === "Chinese" ? "自动清算" : "Automatic liquidation")}
          </Button>
            <Button>
              {languages === "Korean" ? "수동 청산" : (languages === "Chinese" ? "手动清算" : "Manual clearing")}
            </Button></figure></li>
          <li><b>{languages === "Korean" ? "당일 청산" : (languages === "Chinese" ? "当天清算" : "Clearing on the same day")}</b>
            <InputNumber
              size="large"
              defaultValue={0.1}
              min={0.1}
              max={1}
              step="0.1"
              formatter={(value) => `${value}%`}
              parser={(value) => value.replace('%', '')}
              onChange={change_input} /></li>
          <li><b>{languages === "Korean" ? "미체결 수익 범위" : (languages === "Chinese" ? "未签订收益范围" : "Pending income scope")}</b>
            <InputNumber
              size="large"
              defaultValue={0.1}
              min={0.1}
              max={1}
              step="0.1"
              formatter={(value) => `${value}%`}
              parser={(value) => value.replace('%', '')}
              onChange={change_input} /></li>
          <li><b>{languages === "Korean" ? "미체결 청산 범위" : (languages === "Chinese" ? "未签订清算范围" : "Pending liquidation scope")}</b>
            <InputNumber
              size="large"
              defaultValue={0.1}
              min={0.1}
              max={1}
              step="0.1"
              formatter={(value) => `${value}%`}
              parser={(value) => value.replace('%', '')}
              onChange={change_input} /></li>
          <li><b>{languages === "Korean" ? "확인 시간 간격" : (languages === "Chinese" ? "确认时间间隔" : "Confirmation interval")}</b>
            <TimePicker allowClear={false} showNow={false} value={dayjs(timeValue1, format1)} onChange={change_time1} size="large" format={format1} /></li>
        </ul>
      </div>,
    },
    {
      label: languages === "Korean" ? "개인정보 설정" : (languages === "Chinese" ? "隐私设置" : "Privacy setting"),
      key: '2',
      children: <div className='tabs_main'>
        <ul>
          <li><b>{languages === "Korean" ? "전화번호" : (languages === "Chinese" ? "电话号码" : "Phone number")}</b>
            <i>010-9999-9999</i>
            <Button onClick={() => (setIsModalOpen(true), setModalTitle(languages === "Korean" ? "전화번호 변경" : (languages === "Chinese" ? "电话号码变更" : "Phone number change")), setLabel({ label1: languages === "Korean" ? "기존 전화번호" : (languages === "Chinese" ? "旧电话号码" : "Old phone number"), label2: languages === "Korean" ? "변경할 전화번호" : (languages === "Chinese" ? "请输入新电话号码" : "New number"), label3: languages === "Korean" ? "전화번호 재입력" : (languages === "Chinese" ? "再次输入新电话号码" : "Re-enter phone number") }))}>{languages === "Korean" ? "수정" : (languages === "Chinese" ? "编辑" : "Edit")}</Button>
          </li>
          <li><b>{languages === "Korean" ? "비밀번호" : (languages === "Chinese" ? "密码" : "Password")}</b>
            <i>{gePass(999999999999)}</i>
            <Button onClick={() => (setIsModalOpen(true), setModalTitle(languages === "Korean" ? "비밀번호 변경" : (languages === "Chinese" ? "更改密码" : "Change Password")), setLabel({ label1: languages === "Korean" ? "기존 비밀번호" : (languages === "Chinese" ? "旧密码" : "Old password"), label2: languages === "Korean" ? "변경할 비밀번호" : (languages === "Chinese" ? "请输入新密码" : "New password"), label3: languages === "Korean" ? "비밀번호 재입력" : (languages === "Chinese" ? "再次输入新密码" : "Re-enter password") }))}>{languages === "Korean" ? "수정" : (languages === "Chinese" ? "编辑" : "Edit")}</Button>
          </li>
          <li><b>{languages === "Korean" ? "추천인 전화번호" : (languages === "Chinese" ? "推荐人电话号码" : "Recommander Phone")}</b>
            <i>010-9999-9999</i>
            <Button onClick={() => (setIsModalOpen(true), setModalTitle(languages === "Korean" ? "전화번호 변경" : (languages === "Chinese" ? "电话号码变更" : "Phone number change")), setLabel({ label1: languages === "Korean" ? "기존 전화번호" : (languages === "Chinese" ? "旧电话号码" : "Old phone number"), label2: languages === "Korean" ? "변경할 전화번호" : (languages === "Chinese" ? "请输入新电话号码" : "New number"), label3: languages === "Korean" ? "전화번호 재입력" : (languages === "Chinese" ? "再次输入新电话号码" : "Re-enter phone number") }))}>{languages === "Korean" ? "수정" : (languages === "Chinese" ? "编辑" : "Edit")}</Button>
          </li>
          {
            referrer.tel ? <li><b>{languages === "Korean" ? "추천인" : (languages === "Chinese" ? "推荐人" : "Recommander")}</b>
              <i className='referrer'>{referrer.telephone}</i>
              <em></em>
            </li> : <li><b>{languages === "Korean" ? "추천인" : (languages === "Chinese" ? "推荐人" : "Recommander")}</b>
              <Input onChange={(e) => changeTel(e)} size="large" />
              <Button onClick={() => setReferrer({ tel: "888888888", telephone })}>{languages === "Korean" ? "확인" : (languages === "Chinese" ? "确认" : "OK")}</Button>
            </li>
          }
        </ul>
        <section><Tabs defaultActiveKey="1" onChange={tabChange} items={item_pay} centered /></section>
        <div className='footer'>
          <dl>
            <dd>{languages === "Korean" ? "주의사항" : (languages === "Chinese" ? "注意事项" : "Precautions")}</dd>
            <dt>{languages === "Korean" ? " · 추천인은 가입 후 10일 이내에만 입력할 수 있습니다." : (languages === "Chinese" ? " · 推荐人只能在注册后 10 天内输入。" : " · Referrals can only be entered within 10 days of signing up.")}</dt>
            <dt>{languages === "Korean" ? " · 추천인 란에는 추천인의 전화번호를 입력하셔서 추가하실 수 있습니다." : (languages === "Chinese" ? " · 您可以通过在推荐人电话号码栏中输入推荐人的电话号码来添加推荐人。" : " · You can add a recommender by entering the phone number of the recommender in the recommender field.")}</dt>
          </dl>
        </div>
      </div>,
    },
    {
      label: "language",
      key: '3',
      children: <div className='tabs_main'>
        <ul>
          <li>
            <Cascader
              size="large"
              allowClear={false}
              options={options}
              onChange={CascaderChange}
              defaultValue={languages}
            /></li>
        </ul>
      </div>
    },
  ]

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("전화번호 변경");
  const [label, setLabel] = useState({})
  const forms = useRef();


  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const handleOk = () => {
    console.log("ok")
    forms.current.form.validateFields().then(async (values) => {
      console.log(values, '666')
      forms.current.form.resetFields();
      setIsModalOpen(false)
    }).catch((err) => {
      console.log(err)
    })
  }
  useEffect(() => {
    console.log(forms, 'form')
  }, [isModalOpen])
  return (
    <div className='setting'>
      <Avatars username={username} level="Lv.99" coupon="ID" balance="abcd113@defghij.com" icon={<UserIcon />} />
      <div className='main'>
        <Tabs defaultActiveKey="1"
          animated={false}
          centered
          items={items} />
      </div>

      <Modal className='modal_set' title={modalTitle} open={isModalOpen} onCancel={handleCancel} width={800} footer={null} onOk={handleOk} centered>
        <figcaption><Forms labels={label} ref={forms}></Forms></figcaption>
        <Button onClick={handleCancel}>{languages === "Korean" ? "취소" : (languages === "Chinese" ? "取消" : "Cancel")}</Button>
        <Button onClick={handleOk}>{languages === "Korean" ? "확인" : (languages === "Chinese" ? "确认" : "OK")}</Button>
      </Modal>
      {
        spin && <div className='spin'><Spin size="large" /></div>
      }
    </div>
  )
}
